package com.cb.web.wasf.tag;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.tagext.TryCatchFinally;

/**
 * @author CBO
 */
public class SubmitButtonTag extends TagSupport implements TryCatchFinally {

    private String caption;
    private String event;

    public void setCaption(String caption) {
        this.caption = caption;
    }

    public void setEvent(String event) {
        this.event = event;
    }

    @Override
    public int doEndTag() throws JspException {
        StringBuilder sb = new StringBuilder();
        sb.append("<a href=\"#\" class=\"wasf-button\"");
        if (id != null) {
            sb.append(" id=\"").append(id).append("\"");
        }
        sb.append(" onClick=\"");
        // @TODO : Handle special characters, introduce StringUtils.isBlank, use id if event is null
        if (event != null) {
            sb.append("$('#").append(getParentForm().getId()).append("-event').val('").append(event).append("');");
            if (id != null) {
                sb.append("$('#").append(getParentForm().getId()).append("-eventSource').val('").append(id).append("');");
            }
        }
        // @TODO : Handle special characters
        sb.append("$('#").append(getParentForm().getId()).append("').submit();return false;");
        sb.append("\">");
        sb.append(caption);
        sb.append("</a>");
        try {
            pageContext.getOut().print(sb.toString());
        } catch (IOException ioe) {
            throw new JspException(ioe);
        }
        return EVAL_PAGE;
    }

    private FormTag getParentForm() {
        return (FormTag) findAncestorWithClass(this, FormTag.class);
    }

    @Override
    public void doCatch(Throwable throwable) throws Throwable {
        throw throwable;
    }

    @Override
    public void doFinally() {
        id = null;
        caption = null;
        event = null;
    }
}
